/*

*/


define(
   [
      'dojo/_base/declare',
      'dojo/_base/lang',
      'dojo/_base/array',
      'dojo/aspect',
      'dijit/Menu',
      'dijit/MenuItem',
      'dijit/focus'
   ],
   function(declare, lang, array, aspect, Menu, MenuItem, focusUtil)
   {
      return declare([Menu],
      {
         postCreate: function()
         {
            this.inherited(arguments);
            if(this.mTarget)
               this.bindDomNode(this.mTarget.domNode);

            this.mLoadingItem = new MenuItem({
               label:"Loading...",
               iconClass:"dijitIcon icons-fugue-icons-16x16-clock",
               custId:"loading",
               disabled: true
            });
         },
         destroy: function()
         {
            var pMenuItems = this.getChildren();
            for(var i = 0; i < pMenuItems.length; ++i)
            {
               this.removeChild(pMenuItems[i]);
               if(pMenuItems[i] === this.mLoadingItem)
                  continue;

               pMenuItems[i].destroy();
               pMenuItems[i].menuData = null;
            }

            this.inherited(arguments);
         },
         onOpen: function()
         {
            if(this.mDeferred)
               this.mDeferred.cancel();

            if(!this.mLoadingFunction)
            {
               this.inherited(arguments);
               return;
            }

            var pMenuItems = this.getChildren();
            array.forEach(pMenuItems, lang.hitch(this, function(item)
            {
               this.removeChild(item);
               if(item == this.mLoadingItem)
                  return;

               item.destroy();
            }));

            this.mDeferred = this.mLoadingFunction();
            if(!this.mDeferred)
            {
               this.onCancel();
               return;
            }

            this.addChild(this.mLoadingItem);
            this.inherited(arguments);

            this.mDeferred.then(lang.hitch(this, function(data)
            {
               this.mDeferred = null;
               this.createMenu(data);
               var pMenuItems = this.getChildren();
               if(pMenuItems.length > 1)
               {
                  var firstNonLoadingItem = pMenuItems[1];
                  focusUtil.focus(firstNonLoadingItem.domNode);
               }
               this.removeChild(this.mLoadingItem);
            }));
         }
      });
   }
);
